package com.springcloud.thread.web;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 测试
 * @author: linjinp
 * @create: 2019-07-02 14:16
 **/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/thread")
public class CountDownLatchTest {

    public long ThreadTest(int nThreads, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);

        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (int i = 0; i < nThreads; i++) {
            Thread t = new Thread(() -> {
                try {
                    // startGate 进入阻塞，直到 startGate 值为 0
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
        long start = System.nanoTime();
        // startGate 递减
        // 上面会启动 N 个线程，都会等到 startGate == 0 才会去运行 task 线程
        System.out.println("开始运行线程");
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        System.out.println("nThread 运行结束");
        return end - start;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(new CountDownLatchTest().ThreadTest(10, new Test1()));
    }
}

class Test1 implements Runnable {

    @Override
    public void run() {
        System.out.println(new Date());
    }
}